<!--
 * @Date: 2024-10-23 12:53:50
 * @Author: LiSong
 * @LastEditors: LiSong
 * @LastEditTime: 2024-12-23 14:22:15
 * @Description: 完善项目
-->
<template>
	<div class="proj-filling-wrapper">
		<PanelHeaderToolbar 
			:value="panelState.renderData.agName || '暂无'"
			:showTempSave="false"
			@cancel="handleClose"
			@confirm="handleConfirm"
			@tempSave="handleTempSave"
		/>
		<div class="proj-filling-body">
			<div class="filling-body-center">
				<FpRender
					ref="formRenderRef"
					:="formRenderAttrs"
					:formData="panelState.renderData"
					@loaded="formRenderLoaded"
				/>
			</div>
		</div>
	</div>
</template>

<script setup>
import XEUtils from 'xe-utils';
import { blobAxios, defAxios as request, encryptAxios } from '@/utils/http';

import { ElMessage, ElLoading } from 'element-plus';
import { computed, nextTick, reactive, toRaw } from 'vue';

import { FpRender } from '@fp';
import PanelHeaderToolbar from '../comps/PanelHeaderToolbar.vue'

import { useEnv } from '@/hooks/useEnvHook'
import { commonFillProps } from '../cfg/panel-props';
import { useProjectApi, useProjectInfoApi } from '@/api';

const emits = defineEmits(['save', 'close', 'loaded', 'confirm']);

const props = defineProps({
	...commonFillProps,
	type: { type: String, default: 'improve' },
	perfectId: { type: String },
  formCodeA: { type: String },
  formCodeB: { type: String },
});

// 表单渲染组件引用对象
const formRenderRef = ref();
// 表单渲染组件属性
const formRenderAttrs = reactive({
	...props,
	bondTypeCode: '2',
})
// 面板数据集
const panelState = reactive({
	loading: false,
	loadService: null,
	renderData: {},
	initParams: {},
})
/**
 * 加载数据
 * @param {Object} config 配置参数
 */
const loadData = async () => {
	const config = XEUtils.clone(props, true)
	console.log('config', config)
	const isAddStatus = (config.buttonCode === 'add')
	panelState.loadService = ElLoading.service({ fullscreen: true, text: '加载中......' });
	try {
		const queryParams = { ...config, formCode: config.formCodeA, isAddStatus }
		// TODO 如果为安徽环境，添加参数标识处理
		if (useEnv().isAnhuiEnv) { queryParams['busiType'] = 'PRO_PERFECT' }
		const projInfo = await useProjectInfoApi().getProjectInfo(queryParams)
		// 数据赋值
		panelState.renderData = {
			...config, ...projInfo,
			"agName": projInfo['AGENCY_NAME'] || config['agName'],
			"agCode": projInfo['AGENCY_CODE'] || config['agCode'],
			// 设置项目种类 1-一般 2-专项
			"BOND_TYPE_CODE": projInfo['BOND_TYPE_CODE'] || config['BOND_TYPE_CODE']
		}
		// 设置源申报ID
    if (isAddStatus) {
			panelState.renderData['SOURCE_APPLY_ID'] = projInfo['SOURCE_APPLY_ID'] || config['applyId'];
		}
		// 初始数据赋值
		panelState.initParams = {
			...config,
			"agName": projInfo['AGENCY_NAME'] || config['agName'],
			"agCode": projInfo['AGENCY_CODE'] || config['agCode']
		}
		// 根据特定字段属性设置表单编码
    if (projInfo['IS_REPORT'] && projInfo['IS_REPORT'] == '1') {
			formRenderAttrs.formType = 'improve'
			formRenderAttrs.formCode = props.formCodeB
		} else {
			formRenderAttrs.formType = 'edit'
      formRenderAttrs.formCode = props.formCodeA
		}
	} catch(error) {
		panelState.loading = false
		panelState.loadService.close()
	}
	// TODO 临时添加设置类型
	panelState.renderData['bondTypeCode'] = '2'
	// TODO LOAD FORM 加载表单配置信息
	nextTick(() => { formRenderRef.value.loadFormInfo() })
	console.log('loadData', toRaw(panelState), toRaw(formRenderAttrs))
};

/**
 * 取消方法
 */
const handleClose = () => {
	emits('close');
};
/**
 * 暂存按钮点击方法
 */
const handleTempSave = async () => {
	let flag = true

	const { validateField, validateSlotsData } = formRenderRef.value;
	// 校验项目名称
	const proNamevalid = await validateField('PRO_NAME');
	flag = flag && proNamevalid
	if (!proNamevalid) {
		ElMessage.error('基本信息：请填写项目名称！');
		return;
	}

	// 校验立项年度
	const setupYearValid = await validateField('SETUP_YEAR');
	flag = flag && setupYearValid
	if (!setupYearValid) {
		ElMessage.error('前期准备：请填写立项年度！');
		return;
	}
	
	// TODO 四川环境时才对绩效目标表格数据进行校验
	if (useEnv().isAnhuiEnv) {
		// 对绩效目标表格数据进行长度校验
		const jxmbTabValid = await validateSlotsData('ProjectJxmbTable', { checkRequired: false, checkLength: true })
		flag = flag && jxmbTabValid
		if (!jxmbTabValid) return
	}
	
	if (!flag) return
	handleSave(1, () => { emits('save'); });
};
/**
 * 确定按钮点击方法
 */
const handleConfirm = async () => {
	const { validateFormData } = formRenderRef.value;
	const valid = await validateFormData();
	if (!valid) return
	handleSave(2, () => { emits('confirm') });
};

/**
 * 保存数据的方法
 * 
 * @param isTemp 是否暂存 1-是 2-否
 * @param callback 回调函数
 */
const handleSave = async (isTemp = 1, callback) => {
	const { getRenderFormData } = formRenderRef.value;
	getRenderFormData().then(async (params) => {
		const { isBgtAg } = props 
		const { initParams } = panelState
		const { dataArray, slotsData } = params;
		const reqParams = {
			isTemp, data: dataArray,
			...initParams,
			...slotsData,
			'AGENCY_ID': isBgtAg === '1' ? initParams.agId : '',
			'AGENCY_CODE': isBgtAg === '1' ? initParams.agCode : '',
			'AGENCY_NAME': isBgtAg === '1' ? initParams.agName : '',
			'NON_AGENCY_ID': isBgtAg === '1' ? initParams.agId : '',
			'NON_AGENCY_CODE': isBgtAg === '1' ? initParams.agCode : '',
			'NON_AGENCY_NAME': isBgtAg === '1' ? initParams.agName : '',
		};
		console.log('reqParams', reqParams)
		const saveLoading = ElLoading.service({ fullscreen: true, text: '信息正在保存中......' });
		try {
			const res = await encryptAxios({
        url: '/proResPerfect/saveProResPerfect',
        method: 'POST',
        data: reqParams,
			})
			if (res.code === 200) {
				ElMessage.success('保存成功！');
				callback();
			} else {
				console.error(res.msg)
				ElMessage.error(res.msg);
			}
			saveLoading.close();
		} catch (error) {
			console.error(error)
			saveLoading.close();
		}
	});
};
// ----- 表单渲染相关内容
const formRenderLoaded = () => {
	panelState.loading = false
	if (panelState.loadService) { panelState.loadService.close() }
	emits('loaded');
};

loadData(XEUtils.clone(props, true));

</script>

<style lang="scss" scoped>
.proj-filling-wrapper {
	height: 100%;
	display: flex;
	flex-direction: column;
	.proj-filling-body {
		flex: 1;
		min-height: 100px;
		display: flex;
		flex-direction: column;
		.filling-body-center {
			height: 100%;
		}
	}
}
</style>
